/*
 *  cda/src/huffcode.c
 *
 *  (C) 2011 Harry Wei
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>

#include "../include/cda.h"

/*
 * creat_huffmancode: creat huffman code.
 * @get_huff: huffman tree.
 * @hc: allocated sturcture arraies for storing the huffman code.
 * @effect_fre: effective characters && their frequencies.
 * @counter: effective characters' amounts.
 */

int 
creat_huffmancode(struct huffman *get_huff, struct huffcode *hc, 
				struct ch_fre *effect_fre, int counter)
{
	int i;
	int ch_counter;
	int fre = CHAR_USE - 1;
	int start = 1;
	int rem;
	int par;

	for (i = 1; i < counter + 1; i++) {
		for (ch_counter = 1; ch_counter < counter + 1; ch_counter++) {
			if ((get_huff[i].weight == effect_fre[ch_counter].fre) &&
						(effect_fre[ch_counter].check == 0)) {
				fre = CHAR_USE - 1;
				rem = i;
				par = get_huff[i].parent;
				while (0 != par) {
					if (get_huff[par].lchild == rem)
						hc[start].code[fre] = 1;
					else 
						hc[start].code[fre] = 0;
					fre = fre - 1;
					rem = par;
					par = get_huff[rem].parent;
				}
				hc[i].ch = effect_fre[ch_counter].ch;
				effect_fre[ch_counter].check = 1;
				break;
			}
		}
		hc[start].begin = fre + 1;
		start += 1;
	}
	return 0;
}
